package com.regretbuying.front.controller;

import com.alibaba.fastjson.JSON;
import com.regretbuying.front.service.member.MemberService;
import com.regretbuying.front.service.shopping_cart.CartService;
import com.regretbuying.pojo.Member;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Controller
public class LoginController {

    @Resource(name = "fmsi")
    private MemberService memberService;

    @Resource(name = "fcasi")
    private CartService cartService;

    @RequestMapping(value = "/ajaxLogin", produces = {"json/application;charset=UTF-8"})
    @ResponseBody
    public String ajaxLogin(String name, String password, HttpSession session) {

        Map result = new HashMap() ;

        Member login = memberService.getMember(name, password) ;
        if(login != null) {
            result.put("success", true) ;
            result.put("memid", login.getMemberId()) ;

            session.setAttribute("login", login);

            //获取购物车商品数量
            int cartCount = cartService.getGoodsCount(login.getMemberId()) ;
            session.setAttribute("cartCount", cartCount);
            result.put("cartCount", cartCount) ;
        }
        else {
            String msg = "用户名或密码不正确" ;
            result.put("success", false) ;
            result.put("msg", msg) ;
        }

        String json = JSON.toJSONString(result) ;

        return json ;
    }

    @RequestMapping("/login")
    public String login(String name, String password, HttpSession session, Model model) {

        Member login = memberService.getMember(name,password) ;
        if(login != null) {
            session.setAttribute("login", login);

            //获取购物车商品数量,和总价格
            int cartCount = cartService.getGoodsCount(login.getMemberId()) ;
            double priceCount = cartService.CountUnitPrice(login.getMemberId());


            session.setAttribute("cartCount", cartCount);
            session.setAttribute("priceCount",priceCount);
        }
        else {
            String msg = "用户名或密码不正确" ;
            model.addAttribute("msg", msg) ;
            return "front/login" ;
        }
        return "redirect:/index" ;
    }
}
